package com.pri.chat.activity;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.entity.LocalMedia;
import com.netease.nim.uikit.net.SharedHelper;
import com.netease.nim.uikit.net.entity.BaseBean;
import com.netease.nim.uikit.net.entity.DTBean;
import com.netease.nim.uikit.net.rxjava.HttpMethods;
import com.netease.nim.uikit.net.subscribers.ProgressSubscriber;
import com.netease.nim.uikit.net.subscribers.SubscriberOnNextListener;
import com.pri.chat.R;
import com.pri.chat.adapter.DTAdapter;
import com.pri.chat.base.BaseActivity;
import com.pri.chat.dialog.DialogUtil;
import com.pri.chat.model.DTModel;
import com.pri.chat.model.SayModel;
import com.pri.chat.model.ZanModel;
import com.pri.chat.utils.Des3Util;
import com.pri.chat.utils.GlideEngine;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.vondear.rxtool.RxActivityTool;
import com.vondear.rxtool.view.RxToast;

import java.util.ArrayList;
import java.util.List;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;
import butterknife.BindView;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * 描述：添加类的描述
 *
 * @author wx5e48d604c2885118
 * @time 2020/4/24
 */
public class MyDtActivity extends BaseActivity implements BaseQuickAdapter.OnItemChildClickListener ,BaseQuickAdapter.OnItemClickListener{
    @BindView(R.id.rec_main)
    RecyclerView recMain;
    @BindView(R.id.none)
    ImageView none;
    @BindView(R.id.srl_all)
    SmartRefreshLayout srlAll;
    private void refresh() {
        isShowDialog = false;
        page = 1;
        mList.clear();
        mAdapter.notifyDataSetChanged();
        initData();
    }
    private void initSrl() {
        srlAll.setOnRefreshListener(refresh_layout -> {
            refresh_layout.finishRefresh(1000);
            refresh();
        });
        srlAll.setOnLoadmoreListener(refresh_layout -> {
            refresh_layout.finishLoadmore(1000);
            isShowDialog = false;
            page++;
            initData();
        });
    }
    private List<DTBean> mList;
    private DTAdapter mAdapter;
    private void init() {
        mList=new ArrayList<>();
        ((SimpleItemAnimator)recMain.getItemAnimator()).setSupportsChangeAnimations(false);
        LinearLayoutManager linearLayoutManager =new LinearLayoutManager(this);
        recMain.setLayoutManager(linearLayoutManager);
        mAdapter=new DTAdapter(R.layout.item_dt,mList);
        recMain.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(this);
        mAdapter.setOnItemChildClickListener(this);
        mAdapter.setOnImageClickListener((view, c_pos, f_pos) -> {
            PictureSelector.create(this)
                    .themeStyle(R.style.picture_default_style)
                    .isNotPreviewDownload(true)
                    .loadImageEngine(GlideEngine.createGlideEngine()) // 请参考Demo GlideEngine.java
                    .openExternalPreview(c_pos, mList.get(f_pos).getMediaList());
        });

    }
    private int page=1;
    private boolean isShowDialog=true;
    @Override
    protected int getLayoutId() {
        return R.layout.activity_my_dt_layout;
    }

    @Override
    protected void initView() {
        setTitle("我的动态");
        init();
        initSrl();

    }

    @Override
    protected void initData() {
        SubscriberOnNextListener<BaseBean<List<DTBean>>> onNextListener = baseBean -> {
            if(baseBean.getData().isEmpty()&&page==1){
                none.setVisibility(View.VISIBLE);
                mAdapter.notifyDataSetChanged();
                RxToast.normal(getString(R.string.no_data));
            }else {
                none.setVisibility(View.INVISIBLE);
                mList.addAll(baseBean.getData());
                for(int i=0;i<mList.size();i++){
                    String imgs[]=mList.get(i).getPicList().split(",");
                    List<String> list =new ArrayList<>();
                    List<LocalMedia> mediaList =new ArrayList<>();
                    for(int j=0;j<imgs.length;j++){
                        LocalMedia localMedia=new LocalMedia();
                        list.add(imgs[j]);
                        localMedia.setPath(imgs[j]);
                        mediaList.add(localMedia);

                    }
                    mList.get(i).setImgs(list);
                    mList.get(i).setMediaList(mediaList);
                }
                mAdapter.notifyDataSetChanged();
            }
        };

        String lat = SharedHelper.readValueByKeyForString(this,"lat");
        String lng = SharedHelper.readValueByKeyForString(this,"lng");

        DTModel dtModel = new DTModel(page,0, SharedHelper.readId(this),lat, lng,"","");//登录上传参数
        dtModel.setSendMemberId(SharedHelper.readId(this));
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), Des3Util.getJiaMi(dtModel));
                HttpMethods.getInstance().dt_list(new ProgressSubscriber<>(onNextListener, this, isShowDialog), requestBody);

    }


    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        switch (view.getId()){
            case R.id.zanLinear:
                httpLike(position);
                break;
            case R.id.iv_logo:
                Bundle bundle =new Bundle();
                bundle.putString("id",mList.get(position).getMemberId());
                RxActivityTool.skipActivity(MyDtActivity.this, OtherPeopleMsgActivity.class,bundle);
                break;
            case R.id.tv_say_hello:
                if(SharedHelper.readId(this).equals(mList.get(position).getMemberId())){
                    RxToast.normal("不能给自己打招呼");
                }else {
                    httpSayHello(position);
                }
                break;
            case R.id.iv_share:
                if(!mList.get(position).getImgs().get(0).isEmpty()){
                    initShareDialog(mList.get(position).getImgs().get(0),position);
                }else {
                    initShareDialog("",position);
                }

                break;
        }
    }
    private Dialog mShareDialog;
    private void initShareDialog(String path,int pos) {
        mShareDialog= DialogUtil.getInstance().showShareDialog(this,1);
        DialogUtil.getInstance().setOnShareClickListener(new DialogUtil.OnShareClickListener() {
            @Override
            public void qqOnClick(View v) {
                Bundle bundle = new Bundle();
                bundle.putString("id",mList.get(pos).getId());
                bundle.putString("image",path);
                bundle.putString("title",mList.get(pos).getMemberName());
                bundle.putString("content",mList.get(pos).getContent());
                bundle.putInt("type",0);
                RxActivityTool.skipActivity(mContext, ShareMemberActivity.class,bundle);
                mShareDialog.dismiss();
            }

            @Override
            public void circleOnClick(View v) {
                mShareDialog.dismiss();
            }

            @Override
            public void qZoneOnClick(View v) {

            }

            @Override
            public void weixinOnClick(View v) {
                mShareDialog.dismiss();
            }

            @Override
            public void jubaoOnClick(View v) {

            }
        });
        mShareDialog.show();
    }

    private void httpSayHello(int position) {
        SubscriberOnNextListener<BaseBean> onNextListener = baseBean -> {
            RxToast.normal("打招呼成功");

        };
        SayModel userModel = new SayModel();
        userModel.setMemberId(SharedHelper.readId(this));
        userModel.setOtherMemberId(mList.get(position).getMemberId());
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), Des3Util.getJiaMi(userModel));
        HttpMethods.getInstance().callMember(new ProgressSubscriber<>(onNextListener, this, true), requestBody);
    }



    private static final String TAG = "DTFragment";
    private void httpLike(int pos) {
        SubscriberOnNextListener<BaseBean> onNextListener = baseBean -> {
            Log.d(TAG, "onNext: " + baseBean.toString());
            if(mList.get(pos).getSfdz()==0){
                mList.get(pos).setSfdz(1);
                mList.get(pos).setZanNum(mList.get(pos).getZanNum()+1);
            }else {
                mList.get(pos).setSfdz(0);
                mList.get(pos).setZanNum(mList.get(pos).getZanNum()-1);
            }
            mAdapter.notifyItemChanged(pos);
            RxToast.normal(baseBean.getMsg());
        };
        ZanModel zanModel = new ZanModel();
        zanModel.setBdzId(mList.get(pos).getId());
        zanModel.setDzrId(SharedHelper.readId(this));
        zanModel.setType(0);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"),Des3Util.getJiaMi(zanModel));
        HttpMethods.getInstance().saveDianZan(new ProgressSubscriber<>(onNextListener, this, true), requestBody);
    }
    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        Intent intent =new Intent(this, DTmsgActivity.class);
        Bundle bundle_2 = new Bundle();
        bundle_2.putParcelable("dt", mList.get(position));
        intent.putExtras(bundle_2);
        startActivityForResult(intent,0x10);
    }
}
